<template>
  <div class="page_content">
    <header>
      <van-nav-bar class="main_header member_header" title="团体会员">
        <template #left>
          <span @click="goBack">返回</span>
        </template>
        <template #right>
          <van-popover
            v-model="showPopover"
            trigger="click"
            placement="bottom-end"
            theme="dark"
            :actions="actions"
            @select="onPopoverSelect"
          >
            <template #reference>
              <van-icon name="add-o" color="#000" size="18px" style="padding: 0 16px;" />
            </template>
          </van-popover>
        </template>
      </van-nav-bar>
    </header>
    <div class="main_content">
      <div v-if="memberLoading" class="page_loading">
        <van-loading size="24px" vertical color="#fff">加载中...</van-loading>
      </div>
      <div class="tags_list">
        <van-button
          :type="!registerQO.RegisterTags.length ? 'info' : 'default'"
          size="small"
          class="gl_mr_10"
          @click="handleClickRegisterTag('')"
        >
          全部
        </van-button>
        <van-button
          v-for="item in dict.registerTagType"
          :key="item.code"
          :type="registerQO.RegisterTags === item.code ? 'info' : 'default'"
          size="small"
          class="gl_mr_10"
          @click="handleClickRegisterTag(item.code)"
        >
          {{ item.value }}
        </van-button>
      </div>
      <div v-if="memberList.length" class="member_list">
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
          <van-list
            v-model="loading"
            :finished="finished"
            finished-text=""
            error-text="请求失败，点击重新加载"
            :error.sync="error"
            @load="getMemberList"
          >
            <van-collapse v-model="activeName">
              <van-collapse-item v-for="(item, index) in memberList" :key="index" class="member_item" :name="index">
                <template #title>
                  <div class="left_img">
                    <van-image
                      round
                      width="50"
                      height="50"
                      :src="getStaticFileUrl(item.imagePath)"
                      @click="imagePreview(item.imagePath)"
                    />
                  </div>
                  <div class="right_content">
                    <div class="member_name">{{ item.name }}</div>
                    <div class="member_tags">
                      <van-tag v-for="jtem in item.registerTags" :key="jtem.id" class="gl_mr_10 gl_mt_5" size="medium" plain type="primary">
                        {{ jtem.registerTagType && jtem.registerTagType.name }}
                      </van-tag>
                    </div>
                  </div>
                </template>
                <div class="id_number">
                  <span>证件类型：</span>
                  <span>{{ item.idCardType && item.idCardType.name }}</span>
                </div>
                <div class="id_number">
                  <span>证件号码：</span>
                  <span>{{ item.idCardNumber }}</span>
                </div>
                <div class="phone_number">
                  <span>联系方式：</span>
                  <span>{{ item.phoneNumber }}</span>
                </div>
                <div align="right">
                  <van-button type="default" size="small" class="gl_ml_10" @click="showAddMemberDialog(item)">编辑</van-button>
                  <van-button type="default" size="small" class="gl_ml_10" @click="deleteMember(item)">删除</van-button>
                </div>
              </van-collapse-item>
            </van-collapse>
          </van-list>
        </van-pull-refresh>
      </div>
      <van-empty v-else description="暂无人员数据" />
    </div>
    <add-member ref="addMember" :delegation-id="delegationId" @refreshPage="onRefresh" />
    <invite-member ref="inviteMember" @refreshPage="onRefresh" />
  </div>
</template>
<script>
import { mapState, mapActions } from 'vuex';
import { Api_GET_EventsManagementRegisterQO } from '@/lib/form/game/swaggerForm';
import {
  api_GET_EventsManagementRegister,
  api_GET_EventsManagementRegisterId,
  api_DELETE_EventsManagementDelegationRegisterRegisterId,
  api_POST_EventsManagementUserVerifyIdCardRegisterId
} from '@/extend/api/gameswaggerApi/app';
import addMember from './addMember';
import inviteMember from './inviteMember';
export default {
  components: {
    addMember,
    inviteMember
  },
  data() {
    return {
      registerQO: new Api_GET_EventsManagementRegisterQO(),
      memberList: [],
      total: 0,
      // 是否处于加载状态
      loading: false,
      // 是否已经加载完成
      finished: false,
      // 是否加载失败
      error: false,
      refreshing: false,
      activeName: [],
      showPopover: false,
      delegationId: '',
      actions: [
        {
          code: 'addMember',
          text: '添加人员'
        },
        {
          code: 'inviteMember',
          text: '邀请人员'
        }
      ],
      memberLoading: false
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict,
      currentUserType: state => state.user.currentUserType
    })
  },
  watch: {
    currentUserType: {
      handler(val) {
        if (!val) return;
        this.getMemberList();
        this.delegationId = this.currentUserType.delegationId;
      }
    }
  },
  created() {
    this.gameId = this.$route.params.id;
    this.getDict();
    if (this.currentUserType) {
      this.getMemberList();
      this.delegationId = this.currentUserType.delegationId;
    }
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict' }),
    // 获取机构人员列表
    getMemberList() {
      if (!this.currentUserType.delegationId) return;
      this.finished = false;
      if (this.refreshing) {
        this.memberList = [];
        this.refreshing = false;
        this.registerQO.Page = 1;
      }
      this.registerQO.SkipCount = (this.registerQO.Page - 1) * this.registerQO.MaxResultCount;
      this.registerQO.IsApproved = null;
      this.registerQO.IncludeTags = true;
      this.registerQO.DelegationId = this.currentUserType.delegationId;
      this.registerQO.IncludeRegisterType = true;
      this.registerQO.IncludeIdCardType = true;
      api_GET_EventsManagementRegister(this.registerQO).then(res => {
        this.total = res.totalCount;
        this.memberList = this.memberList.concat(res.items);
        this.loading = false;
        if (this.total > this.memberList.length) {
          this.registerQO.Page += 1;
        } else {
          this.finished = true;
        }
        this.memberLoading = false;
      }, error => {
        this.loading = false;
        this.$toast.fail(error.error.message);
        this.memberLoading = false;
      });
    },
    onRefresh(code) {
      if (!this.currentUserType.delegationId) return;
      this.memberLoading = true;
      this.finished = false;
      this.refreshing = true;
      if (this.loading) return;
      this.loading = true;
      this.getMemberList();
    },
    handleClickRegisterTag(code) {
      if (!this.currentUserType.delegationId) return;
      this.registerQO.RegisterTags = code || [];
      this.onRefresh();
    },
    // 获取静态文件
    getStaticFileUrl(relativeUrl) {
      if (relativeUrl) {
        return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
      } else {
        return require('@/assets/images/face_default.png');
      }
    },
    goBack() {
      this.$router.push({
        path: `/myCenter${this.gameId && '/' + this.gameId || ''}/team`
      });
    },
    deleteMember(memberInfo) {
      this.$dialog.confirm({
        title: '提示',
        message: `您确定要删除会员[ ${memberInfo.name} ]吗？`
      }).then(() => {
        api_DELETE_EventsManagementDelegationRegisterRegisterId(memberInfo.id).then(res => {
          this.onRefresh();
          this.$toast.success('删除成功');
        }, error => {
          this.$toast.fail(error.error.message);
        });
      });
    },
    // 实名认证
    handleSubmitVerifyIdCard(row) {
      api_POST_EventsManagementUserVerifyIdCardRegisterId(row.id).then(valid => {
        if (valid) {
          this.onRefresh();
          this.$toast.success('实名认证成功');
        } else {
          this.$toast.fail('实名认证失败');
        }
      }, error => {
        this.$toast.fail(error.error.message);
      });
    },
    showAddMemberDialog(personInfo) {
      this.memberLoading = true;
      this.getMemberInfo(personInfo.id).then(res => {
        this.memberLoading = false;
        const _memberInfo = res;
        _memberInfo.registerTags = _memberInfo.registerTags.map(item => item.registerTagTypeCode);
        this.$refs.addMember.open(_memberInfo, personInfo.id);
      }, () => {
        this.memberLoading = false;
      });
    },
    // 获取人员信息
    getMemberInfo(id) {
      return new Promise((resolve, reject) => {
        api_GET_EventsManagementRegisterId(id, { IncludeTags: true }).then(res => {
          resolve(res);
        }, error => {
          reject(error);
          this.$toast.fail(error.error.message);
        });
      });
    },
    onPopoverSelect(action) {
      switch (action.code) {
        // 新增人员
        case 'addMember':
          this.$refs.addMember.open();
          break;
        // 邀请人员
        case 'inviteMember':
          this.$refs.inviteMember.open();
          break;
        default:
          break;
      }
    }
  }
};
</script>
<style>
.tags_list {
  padding: 10px 0 0 10px;
}
.member_list .van-pull-refresh {
  min-height: calc(100vh - 102px);
}
.member_list .van-pull-refresh__track {
  min-height: calc(100vh - 102px);
}
.member_item {
  overflow: hidden;
  border: 1px solid #dbdbdb;
  border-radius: 4px;
  margin: 10px;
}
.member_header .van-nav-bar__right {
  padding: 0 2px;
}
.member_item .van-cell {
  padding: 10px;
}
.member_item .left_img {
  float: left;
  width: 60px;
  padding-right: 10px;
}
.member_item .right_content {
  float: left;
  width: calc(100% - 60px);
}
</style>
